package org.example.config;

import io.grpc.ConnectivityState;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
//import io.grpc.netty.GrpcSslContexts;
//import io.grpc.netty.NettyChannelBuilder;
//import io.netty.handler.ssl.SslContext;
import org.springframework.beans.factory.DisposableBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author wangjun
 * @Date 2025/3/17 18:49
 */
public class SdkGrpcClient implements DisposableBean {

    private List<ManagedChannel> channels = new ArrayList<>(); // Channel列表
    private AtomicInteger currentIndex = new AtomicInteger(0); // 当前索引

    public SdkGrpcClient(Map<String, Integer> serverMap) {
        initializeChannels(serverMap);
    }

    private void initializeChannels(Map<String, Integer> serverMap) {
        try {
            serverMap.forEach((ip, port) -> {
                // 明确初始化两个 Channel（示例）
                ManagedChannel channel1 = ManagedChannelBuilder.forAddress(ip, port)
                        .usePlaintext()  // 明文传输（仅用于测试）
                        .enableRetry()   // 启用重试
                        .maxRetryAttempts(5)
                        .build();
                channels.add(channel1);
                // 可选：等待 Channel 进入 READY 状态（首次调用可能需等待）
//                awaitChannelReady(channel1);
            });
            System.out.println("Channels initialized successfully.");
        } catch (Exception e) {
            System.out.println("Channel initialization failed: " + e.getMessage());
            shutdown(); // 清理资源
            throw new IllegalStateException("Failed to initialize gRPC channels", e);
        }
    }

    private void awaitChannelReady(ManagedChannel channel) throws InterruptedException {
        // 简单等待逻辑（生产环境建议使用异步监听）
        for (int i = 0; i < 5; i++) { // 最多等待 5 秒
            if (channel.getState(true) == ConnectivityState.READY) {
                return;
            }
            Thread.sleep(1000);
        }
        throw new IllegalStateException("Channel failed to reach READY state");
    }


    public ManagedChannel next() {
        int size = channels.size();
        if (size == 0) {
            throw new IllegalStateException("No channels available");
        }
        int current = currentIndex.get();
        for (int i = 1; i <= size; i++) {
            int nextIndex = (current + i) % size;
            if (isChannelActive(channels.get(nextIndex))) {
                currentIndex.set(nextIndex);
                System.out.println("Selected channel index: " + nextIndex);
                return channels.get(nextIndex);
            }
        }
        throw new IllegalStateException("All channels are inactive");
    }

    private boolean isChannelActive(ManagedChannel channel) {
        ConnectivityState state = channel.getState(true); // 主动请求状态更新
        return state == ConnectivityState.READY;
    }

    @Override
    public void destroy() {
        shutdown();
    }

    public void shutdown() {
        channels.forEach(channel -> {
            try {
                channel.shutdown();
            } catch (Exception e) {
                System.err.println("Error shutting down channel: " + e.getMessage());
            }
        });
        channels.clear();
        System.out.println("All gRPC channels shut down.");
    }
}
